import { Component, OnInit } from '@angular/core';

import { Player } from './player';
import { PlayerService } from './http-player.service.promise';

@Component({
    selector: 'guide-player-list-promise',
    templateUrl: './http-player-list.component.html',
    providers: [PlayerService]
})
export class HttpPlayerListPromiseComponent implements OnInit {
    errorMessage: string;
    players: Player[];
    mode = 'Promise';
    selectedPlayer: Player;
    originPlayer: Player;

    constructor(private playerService: PlayerService) { }

    getPlayers() {
        this.playerService.getPlayers()
            .then(
            players => this.players = players,
            error => this.errorMessage = <any>error);
    }
    updatePlayer() {
        if (!this.selectedPlayer) {
            return;
        }
        if (this.selectedPlayer.name === this.originPlayer.name) {
            return;
        }
        this.playerService.updatePlayer(this.selectedPlayer).then(() => {
            this.selectedPlayer = null;
            this.originPlayer = null;
        }, error => this.errorMessage = <any>error);
    }
    ngOnInit() {
        this.getPlayers();
    }
    onSelect(player: Player) {
        this.selectedPlayer = player;
        this.originPlayer = JSON.parse(JSON.stringify(player));
    }
}